package com.x.compute.core.util;


import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * JSR303 Bean Validation工具类
 *
 * @author xuxin
 */
@Slf4j
public class ValidationUtils {

    private ValidationUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static <T> boolean validate(T t) {
        Validator validator = SpringUtil.getBean(Validator.class);
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        if (constraintViolations.isEmpty()) {
            return true;
        }
        log.error("实体类[{}]参数验证错误[{}]", t.getClass().getName(), constraintViolations.toString());
        return false;
    }

    /**
     * 实体参数校验并异常抛出
     * @param t 实体
     * @param <T>
     */
    public static <T> void validateAndThrow(T t) {
        Validator validator = SpringUtil.getBean(Validator.class);
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        if (!constraintViolations.isEmpty()) {
            StringBuilder message = new StringBuilder();
            for (ConstraintViolation<T> c :constraintViolations){
                message.append(c.getMessage()) ;
            }
            log.error("实体类[{}]参数验证错误[{}]", t.getClass().getName(), message.toString());
            throw new IllegalArgumentException(message.toString());
        }
    }

}
